package server.controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;
import plug.result.ReqPage;
import plug.result.RetResponse;
import plug.result.RetResult;
import server.dao.MessageDao;
import server.dao.ShopDao;
import server.model.entity.Message;
import server.model.entity.Shop;

import java.util.List;
import java.util.Optional;

/**
 * 创建人:    xvzhe
 * 创建时间:
 * 修改时间:
 * 版本:      v1.0
 */
@RestController
@RequestMapping("v2/api/shop")
@Api(value = "对外接口（商品）", tags = {"不需登录(商品)"})
@CrossOrigin(origins = "*")
public class SpController {
    @Autowired
    ShopDao shopDao;
    @Autowired
    MessageDao messageDao;

    @ApiOperation("商品列表")
    @PostMapping("/all")
    public RetResult all(@RequestBody ReqPage reqPage) {
        JSONObject req = Optional.ofNullable(reqPage.getCommon()).orElseGet(JSONObject::new);
        Shop entity = JSON.parseObject(req.toJSONString(), Shop.class);
        entity.setStatus(true);
        int page = reqPage.getPage() - 1;
        int size = reqPage.getLimit();
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "name");
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<Shop> example = Example.of(entity, matcher);
        Page<Shop> pages = shopDao.findAll(example, pageable);
        List<Shop> pageList = pages.getContent();
        return RetResponse.makeRsp(0, "成功", pageList, (int) pages.getTotalElements());
    }

    @ApiOperation("商品购买公告")
    @PostMapping("/message")
    public RetResult message() {
        return RetResponse.makeOKRsp(messageDao.findByType(Message.Type.BUY));
    }
}
